#!/usr/bin/env ruby

require 'socket'
require 'server_lib'
require 'data_handler'
include Socket::Constants

begin 
  
  server = TCPServer.new('',5001)
  clients = []
  
  listener = Thread.new do
    # Listen for incoming connections 
    loop do
      begin
        client = server.accept_nonblock
        clients << client
      rescue Errno::EAGAIN, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR
        IO.select([server])
        retry
      end        
      add_client_listener(client)
    end
  end
  
  # Periodically test if the sockets are alive. If not, close them and remove from clients[]
  loop do      
    clients.reject!{|c| c.closed? || (c.keep_alive? ? false : !c.close) }
    puts clients.size
    sleep 2
  end
    
  listener.join
  puts "listener joined"

rescue Interrupt

ensure

  puts "killing the sockets"
  clients.each{|c| c.close unless c.closed? }

end